<template>
  <div class="app-container">
        <el-col :span="24" style="padding: 20px">
          <!-- 高级搜索表单 -->
          <div class="el-advanced-search-container">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              label-width="80px"
              v-show="showSearch"
              class="el-advanced-search-form"
            >
              <!-- 第一行：培训班编号、创建年份、班级状态、开班时间 -->
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="6" :lg="6">
                  <el-form-item label="培训班编号" prop="trainingClassCode" label-width="100px">
                    <el-input
                      v-model="queryParams.trainingClassCode"
                      placeholder="请输入培训班编号"
                      clearable
                      @keyup.enter.native="handleQuery"
                      style="min-width:150px"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6" :lg="6"  label-width="100px">
                  <el-form-item label="创建年份" prop="trainingYear">
                    <el-select
                      v-model="queryParams.trainingYear"
                      placeholder="请选择创建年份"
                      clearable
                      style="min-width:150px"
                    >
                      <el-option
                        v-for="year in yearOptions"
                        :key="year"
                        :label="year"
                        :value="year"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6" :lg="6">
                  <el-form-item label="班级状态" prop="classStatus">
                    <el-select
                      v-model="queryParams.classStatus"
                      placeholder="选择班级状态"
                      clearable
                      style="min-width:150px"
                    >
                      <el-option
                        v-for="dict in dict.type.class_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6" :lg="6">
                  <el-form-item label="培训班名称" prop="trainingClassName" label-width="100px">
                    <el-input
                      v-model="queryParams.trainingClassName"
                      placeholder="请输入培训班名称"
                      clearable
                      @keyup.enter.native="handleQuery"
                      style="min-width:150px"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第二行：培训班名称、班主任、班组人员、开班类型 -->
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                  <el-form-item label="班主任" prop="headTeacherName">
                    <el-input
                      v-model="queryParams.headTeacherName"
                      placeholder="请输入班主任姓名"
                      clearable
                      @keyup.enter.native="handleQuery"
                      style="min-width:150px"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8">
                  <el-form-item label="开班时间" prop="startEndTime">
                    <el-date-picker
                      v-model="dateRange" style="width: 200px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" >
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button type="default" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 操作按钮栏 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="24">
              <!-- 班级列表组 -->
              <el-button-group>
                <el-button disabled>班级列表</el-button>
                <el-button
                  type="primary"
                  plain
                  @click="handleExport"
                  style="margin-left: 4px;border: none;"
                >导出</el-button>
              </el-button-group>

              <!-- 班级列表组 -->
              <el-button-group style="margin-left: 10px">
                <el-button disabled>班级报名</el-button>
                <el-button
                  type="primary"
                  :disabled="single"
                  plain
                  @click="handleSignInQr"
                  style="margin-left: 4px;border: none;"
                >班级二维码</el-button>

                <el-button
                  type="primary"
                  plain
                  @click="toggleSearch"
                  style="margin-left: 200px;border: none;"
                >{{ showSearch ? '隐藏搜索' : '显示搜索' }}</el-button>
                <el-button
                  type="primary"
                  plain
                  @click="handleRefresh"
                  style="margin-left: 4px;border: none;"
                >刷新</el-button>
              </el-button-group>

            </el-col>

            <el-col :span="24">
              <!-- 班级数据组 -->
              <el-button-group>
                <el-button disabled>班级数据</el-button>
                <el-button
                  type="primary"
                  plain
                  @click="handleAdd"
                  style="margin-left: 4px;border: none;"
                >创建班级</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  @click="handleUpdateSingle"
                  style="margin-left: 4px;border: none;"
                >编辑班级信息</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleSetMembers"
                >设置班级信息</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleSetClassStatus"
                >班级结业</el-button>
              </el-button-group>

              <!-- 学员管理组 -->
              <el-button-group>
                <el-button disabled  style="margin-left: 50px;">学员管理</el-button>
                <!-- <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleClassHandover"
                >班级交接</el-button> -->
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleTrainingReservation"
                >培训预约情况</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleClassStudents"
                >内训学员</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleStudentNotice"
                >学员通知</el-button>

                <el-button disabled style="margin-left: 40px;">考试设置</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleClassExam"
                >考试情况</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleClassExamArrange"
                >考试安排</el-button>
              </el-button-group>
            </el-col>

            <el-col :span="24">
              <!-- 过程管理组 -->
              <el-button-group>
                <el-button disabled>过程管理</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleSignIn"
                >签到</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleSignInStatus"
                >签到情况</el-button>
                <el-button disabled style="margin-left: 40px;">班级维护</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleClassRemark"
                >班级备注</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  @click="handleViewSingle"
                  style="margin-left: 4px;border: none;"
                >班级数据维护详情</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  @click="handleClassSatisfaction"
                  style="margin-left: 4px;border: none;"
                >班级满意度</el-button>
                <!-- <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  style="margin-left: 4px;border: none;"
                  @click="handleExportClassDetail"
                >班级详情导出</el-button> -->
                <!-- <el-button
                  type="danger"
                  plain
                  :disabled="multiple"
                  @click="handleDelete"
                  style="margin-left: 4px;border: none;"
                >删除</el-button> -->
              </el-button-group>


              <!-- 结算组 -->
              <el-button-group>
                <el-button
                  plain
                  disabled
                  @click="handleClassSettlement"
                  style="margin-left:50px"
                >班级结算</el-button>
                <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  @click="handleFeeSettlement"
                  style="margin-left: 4px;border: none;"
                >费用结算</el-button>
                <!-- <el-button
                  type="primary"
                  plain
                  :disabled="single"
                  @click="handleExportFeeSettlement"
                  style="margin-left: 4px;border: none;"
                >费用结算导出</el-button> -->
              </el-button-group>
            </el-col>
          </el-row>

          <!-- 数据表格 -->
          <el-table
            v-loading="loading"
            :data="TrainingClassList"
            @selection-change="handleSelectionChange"
            border
            stripe
            :default-sort="{prop: 'createTime', order: 'descending'}"
          >
            <el-table-column type="selection" width="55" align="center" />
             <el-table-column label="培训班编号" align="center" prop="trainingClassCode" width="120" />
            <el-table-column label="培训班名称" align="center" prop="trainingClassName" min-width="180" />
            <el-table-column label="班级状态" align="center" prop="classStatus" width="120">
              <template slot-scope="scope">
                <el-tag
                  :type="
                    scope.row.classStatus === '1' ? 'info' :
                    scope.row.classStatus === '2' ? 'primary' :
                    scope.row.classStatus === '3' ? 'success' : 'danger'
                  "
                >
                  {{ getClassStatusLabel(scope.row.classStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="培训年份" align="center" prop="trainingYear" width="100" />
            <el-table-column label="期次" align="center" prop="trainingSession" width="80" />
            <el-table-column label="培训项目" align="center" prop="trainingProjectNames" />
            <el-table-column label="培训类型" align="center" prop="trainingType" width="120">
              <template slot-scope="scope">
                <el-tag
                  :type="
                    scope.row.trainingType === '1' ? 'info' :
                    scope.row.trainingType === '2' ? 'primary' :
                    scope.row.trainingType === '3' ? 'success':''
                  "
                >
                  {{ getTrainingTypeLabel(scope.row.trainingType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="培训部门" align="center" prop="trainingDepartmentName" />
            <!-- <el-table-column label="培训人数" align="center" prop="totalQuota" width="100" />
            <el-table-column label="报到人数" align="center" prop="registeredCount" width="100" /> -->
            <el-table-column label="报到日期" align="center" prop="registrationDate" width="120">
              <template slot-scope="scope">{{ parseTime(scope.row.registrationDate, '{y}-{m}-{d}') }}</template>
            </el-table-column>
            <el-table-column label="培训周期" align="center" width="200">
              <template slot-scope="scope">
                {{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }} 至 {{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}
              </template>
            </el-table-column>
            <el-table-column label="是否考试" align="center" prop="needExam" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.needExam === '1' ? 'success' : 'info'">
                  {{ scope.row.needExam === '1' ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="培训地区" align="center" prop="trainingRegion" width="100" />
            <el-table-column label="培训地址" align="center" prop="trainingAddress" width="100" />
            <el-table-column label="培训地点" align="center" prop="trainingVenue" width="100" />
            <el-table-column label="实际培训地点" align="center" prop="actualTrainingVenue" width="100" />
            <el-table-column label="班主任1" align="center" prop="headTeacher1Name" width="100" />
            <el-table-column label="班主任2" align="center" prop="headTeacher2Name" width="100" />
            <el-table-column label="附件" align="center" prop="attachments" width="100" />
            <el-table-column label="组成人员" align="center" prop="staffInfo" width="100" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.staffInfo !== null &&scope.row.staffInfo !== '' ? 'success' : 'info'">
                  {{ scope.row.staffInfo !== null &&scope.row.staffInfo !== '' ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="课程" align="center" prop="courseIds" width="100" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.courseIds !== null &&scope.row.courseIds !== '' ? 'success' : 'info'">
                  {{ scope.row.courseIds !== null &&scope.row.courseIds !== '' ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="教师" align="center" prop="teacherIds" width="100" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.teacherIds !== null &&scope.row.teacherIds !== '' ? 'success' : 'info'">
                  {{ scope.row.teacherIds !== null &&scope.row.teacherIds !== '' ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="教材" align="center" prop="teachingMaterialIds" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.teachingMaterialIds !== null &&scope.row.teachingMaterialIds !== '' ? 'success' : 'info'">
                  {{ scope.row.teachingMaterialIds !== null &&scope.row.teachingMaterialIds !== '' ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="耗材" align="center" prop="classSuppliesIds" width="100" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.classSuppliesIds !== null &&scope.row.classSuppliesIds !== ''  ? 'success' : 'info'">
                  {{ scope.row.classSuppliesIds !== null &&scope.row.classSuppliesIds !== '' ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="考试" align="center" prop="examPaperIds" width="100" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.examPaperIds !== null &&scope.row.examPaperIds !== '' ? 'success' : 'info'">
                  {{ scope.row.examPaperIds !== null &&scope.row.examPaperIds !== ''  ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="证书" align="center" prop="certificateId" width="100" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.certificateId !== null &&scope.row.certificateId !== ''  ? 'success' : 'info'">
                  {{ scope.row.certificateId !== null &&scope.row.certificateId !== ''  ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="培训计划" align="center" prop="trainingPlanDesc" width="100" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.trainingPlanDesc !== null &&scope.row.trainingPlanDesc !== '' ? 'success' : 'info'">
                  {{ scope.row.trainingPlanDesc !== null &&scope.row.trainingPlanDesc !== ''  ? '已设置' : '未设置' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template slot-scope="scope">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row)"
                >查看</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
            style="margin-top: 15px"
          />

          <!-- 新增班级弹窗 -->
          <el-dialog
            :title="'添加培训班'"
            :visible.sync="addOpen"
            width="800px"
            append-to-body
            class="dialog-training-class"
            @close="cancelAdd"
          >
            <el-form
              ref="addForm"
              :model="addForm"
              :rules="rules"
              label-width="100px"
            >
              <!-- 班级基本信息板块 -->
              <div class="form-section">
                <h3 class="section-title">班级基本信息</h3>
                <el-row :gutter="20" class="form-row">
                  <!-- 左列 -->
                  <el-col :span="12">
                    <el-form-item label="报名类别" prop="signUpCategory" >
                      <el-select v-model="addForm.signUpCategory" placeholder="请选择报名类别" disabled>
                        <el-option
                          v-for="dict in dict.type.bmlb"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="培训班编号" prop="trainingClassCode">
                      <el-input v-model="addForm.trainingClassCode" placeholder="请输入培训班编号" />
                    </el-form-item>
                    <el-form-item label="年份" prop="trainingYear">
                      <el-select v-model="addForm.trainingYear" placeholder="请选择年份">
                        <el-option
                          v-for="year in getYears"
                          :key="year"
                          :label="year"
                          :value="year"
                        />
                      </el-select>
                    </el-form-item>

                    <!-- 培训部门树形选择框 -->
                    <el-form-item label="培训部门" prop="trainingDepartmentName">
                      <el-select
                        class="main-select-tree"
                        ref="addDeptSelectTree"
                        v-model="addForm.trainingDepartmentName"
                        style="width: 100%;"
                        name='deptSelect'>

                        <el-option
                          v-for="item in optionData(departmentData)"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                          style="display: none;" />

                        <el-tree
                          class="main-select-el-tree"
                          ref="addDeptSelectelTree"
                          :data="departmentData"
                          :props='treeProps'
                          node-key="id"
                          highlight-current
                          @node-click="(node) => handleDeptNodeClick(node, 'add')"
                          :expand-on-click-node="expandOnClickNode"
                          default-expand-all />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="培训部门ID" prop="trainingDepartment" hidden>
                      <el-input v-model="addForm.trainingDepartment" placeholder="请输入培训部门ID" />
                    </el-form-item>
                    <el-form-item label="培训开始日期" prop="startDate" label-width="150px">
                      <el-date-picker
                        v-model="addForm.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择培训开始日期"
                        style="width: 100%;"
                      />
                    </el-form-item>
                    <el-form-item label="培训地区" prop="trainingRegion">
                      <el-input v-model="addForm.trainingRegion" placeholder="请输入培训地区" />
                    </el-form-item>
                    <el-form-item label="培训地点" prop="trainingVenue">
                      <el-input v-model="addForm.trainingVenue" placeholder="请输入培训地点" />
                    </el-form-item>

                  </el-col>
                  <!-- 右列 -->
                  <el-col :span="12">

                    <el-form-item label="培训班名称" prop="trainingClassName">
                      <el-input v-model="addForm.trainingClassName" placeholder="请输入培训班名称" />
                    </el-form-item>
                    <el-form-item label="期次" prop="trainingSession">
                      <el-input v-model="addForm.trainingSession" placeholder="请输入期次" />
                    </el-form-item>
                    <el-form-item label="培训截止日期" prop="endDate" label-width="150px">
                      <el-date-picker
                        v-model="addForm.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择培训截止日期"
                        style="width: 100%;"
                      />
                    </el-form-item>
                    <el-form-item label="培训地址" prop="trainingAddress">
                      <el-input v-model="addForm.trainingAddress" placeholder="请输入培训地址" />
                    </el-form-item>
                    <el-form-item label="实际培训地点" prop="actualTrainingVenue">
                      <el-input v-model="addForm.actualTrainingVenue" placeholder="请输入实际培训地点" />
                    </el-form-item>
                    <!-- 班主任1选择 -->
                    <el-form-item label="班主任1" class="form-item" prop="headTeacher1">
                      <el-select
                        ref="addHeadTeacher1Select"
                        v-model="addForm.headTeacher1"
                        placeholder="请选择班主任1"
                        class="custom-input"
                        @change="handleHeadTeacherChange('headTeacher1', 'add')"
                        clearable
                      >
                        <el-option
                          v-if="memberOptions.length === 0"
                          value=""
                          disabled
                        >
                          人员数据加载中...
                        </el-option>
                        <el-option
                          v-else
                          v-for="user in memberOptions"
                          :key="user.userId"
                          :label="user.nickName || user.userName"
                          :value="user.userId.toString()"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="班级状态" prop="classStatus">
                      <el-select v-model="addForm.classStatus" placeholder="请选择班级状态">
                        <el-option
                          v-for="dict in dict.type.class_status"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 备注信息 -->
              <div class="form-section">
                <h3 class="section-title">备注信息</h3>
                <el-row :gutter="20" class="form-row">
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remarks">
                      <el-input
                        v-model="addForm.remarks"
                        type="textarea"
                        rows="3"
                        placeholder="请输入备注信息（可选）"
                        maxlength="200"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancelAdd">取消</el-button>
              <el-button type="primary" @click="submitAddForm">提交</el-button>
            </div>
          </el-dialog>

          <!-- 编辑班级弹窗 -->
          <el-dialog
            :title="'编辑培训班信息'"
            :visible.sync="editOpen"
            width="800px"
            append-to-body
            class="dialog-training-class"
            @close="cancelEdit"
          >
            <el-form
              ref="editForm"
              :model="editForm"
              :rules="rules"
              label-width="100px"
            >
              <!-- 班级基本信息板块 -->
              <div class="form-section">
                <h3 class="section-title">班级基本信息</h3>
                <el-row :gutter="20" class="form-row">
                  <!-- 左列 -->
                  <el-col :span="12">
                    <el-form-item label="报名类别" prop="signUpCategory">
                      <el-select v-model="editForm.signUpCategory" placeholder="请选择报名类别" disabled>
                        <el-option
                          v-for="dict in dict.type.bmlb"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="培训班编号" prop="trainingClassCode">
                      <el-input v-model="editForm.trainingClassCode" placeholder="请输入培训班编号" />
                    </el-form-item>
                    <el-form-item label="年份" prop="trainingYear">
                      <el-select v-model="editForm.trainingYear" placeholder="请选择年份">
                        <el-option
                          v-for="year in getYears"
                          :key="year"
                          :label="year"
                          :value="year"
                        />
                      </el-select>
                    </el-form-item>

                    <!-- 培训部门树形选择框 -->
                    <el-form-item label="培训部门" prop="trainingDepartmentName">
                      <el-select
                        class="main-select-tree"
                        ref="editDeptSelectTree"
                        v-model="editForm.trainingDepartmentName"
                        style="width: 100%;"
                        name='deptSelect'>

                        <el-option
                          v-for="item in optionData(departmentData)"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                          style="display: none;" />

                        <el-tree
                          class="main-select-el-tree"
                          ref="editDeptSelectelTree"
                          :data="departmentData"
                          :props='treeProps'
                          node-key="id"
                          highlight-current
                          @node-click="(node) => handleDeptNodeClick(node, 'edit')"
                          :expand-on-click-node="expandOnClickNode"
                          default-expand-all />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="培训部门ID" prop="trainingDepartment" hidden>
                      <el-input v-model="editForm.trainingDepartment" placeholder="请输入培训部门ID" />
                    </el-form-item>
                    <el-form-item label="培训开始日期" prop="startDate" label-width="150px">
                      <el-date-picker
                        v-model="editForm.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择培训开始日期"
                        style="width: 100%;"
                      />
                    </el-form-item>
                    <el-form-item label="培训地区" prop="trainingRegion">
                      <el-input v-model="editForm.trainingRegion" placeholder="请输入培训地区" />
                    </el-form-item>
                    <el-form-item label="培训地点" prop="trainingVenue">
                      <el-input v-model="editForm.trainingVenue" placeholder="请输入培训地点" />
                    </el-form-item>
                  </el-col>
                  <!-- 右列 -->
                  <el-col :span="12">

                    <el-form-item label="培训班名称" prop="trainingClassName">
                      <el-input v-model="editForm.trainingClassName" placeholder="请输入培训班名称" />
                    </el-form-item>
                    <el-form-item label="期次" prop="trainingSession">
                      <el-input v-model="editForm.trainingSession" placeholder="请输入期次" />
                    </el-form-item>
                    <el-form-item label="培训截止日期" prop="endDate" label-width="150px">
                      <el-date-picker
                        v-model="editForm.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择培训截止日期"
                        style="width: 100%;"
                      />
                    </el-form-item>
                    <el-form-item label="培训地址" prop="trainingAddress">
                      <el-input v-model="editForm.trainingAddress" placeholder="请输入培训地址" />
                    </el-form-item>
                    <el-form-item label="实际培训地点" prop="actualTrainingVenue">
                      <el-input v-model="editForm.actualTrainingVenue" placeholder="请输入实际培训地点" />
                    </el-form-item>
                    <!-- 班主任1选择 -->
                    <el-form-item label="班主任1" class="form-item" prop="headTeacher1">
                      <el-select
                        ref="editHeadTeacher1Select"
                        v-model="editForm.headTeacher1"
                        placeholder="请选择班主任1"
                        class="custom-input"
                        @change="handleHeadTeacherChange('headTeacher1', 'edit')"
                        clearable
                      >
                        <el-option
                          v-if="memberOptions.length === 0"
                          value=""
                          disabled
                        >
                          人员数据加载中...
                        </el-option>
                        <el-option
                          v-else
                          v-for="user in memberOptions"
                          :key="user.userId"
                          :label="user.nickName || user.userName"
                          :value="user.userId.toString()"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="班级状态" prop="classStatus">
                      <el-select v-model="editForm.classStatus" placeholder="请选择班级状态">
                        <el-option
                          v-for="dict in dict.type.class_status"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 备注信息 -->
              <div class="form-section">
                <h3 class="section-title">备注信息</h3>
                <el-row :gutter="20" class="form-row">
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remarks">
                      <el-input
                        v-model="editForm.remarks"
                        type="textarea"
                        rows="3"
                        placeholder="请输入备注信息（可选）"
                        maxlength="200"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancelEdit">取消</el-button>
              <el-button type="primary" @click="submitEditForm">提交</el-button>
            </div>
          </el-dialog>

          <!-- 查看培训班详情弹窗 -->
          <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body class="dialog-view">
            <el-form :model="viewForm" label-width="100px" class="view-form">
              <!-- 基础信息 -->
              <el-divider content-position="left">基础信息</el-divider>
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="培训班名称">
                    <el-input v-model="viewForm.trainingClassName" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训班编号">
                    <el-input v-model="viewForm.trainingClassCode" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="培训年份">
                    <el-input v-model="viewForm.trainingYear" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="期次">
                    <el-input v-model="viewForm.trainingSession" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="班级状态">
                    <el-input
                      :value="getClassStatusLabel(viewForm.classStatus)"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训类型">
                    <el-input
                      :value="getTrainingTypeLabel(viewForm.trainingType)"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 其他详情内容 -->
              <el-divider content-position="left">培训信息</el-divider>
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="培训部门">
                    <el-input v-model="viewForm.trainingDepartmentName" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训项目">
                    <el-input v-model="viewForm.trainingProjectNames" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="培训人数">
                    <el-input v-model="viewForm.totalQuota" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="报到人数">
                    <el-input v-model="viewForm.registeredCount" disabled />
                  </el-form-item>
                </el-col>
              </el-row> -->
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="是否考试">
                    <el-input :value="viewForm.needExam === '1' ? '是' : '否'" disabled />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-divider content-position="left">时间信息</el-divider>
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="报到日期">
                    <el-input v-model="viewForm.registrationDate" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训开始日期">
                    <el-input v-model="viewForm.startDate" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="培训截止日期">
                    <el-input v-model="viewForm.endDate" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancelView">关闭</el-button>
              <!-- <el-button type="primary" @click="handleViewStudents(viewForm)">进入学员管理</el-button> -->
            </div>
          </el-dialog>
          <!-- 报名备注弹出框 -->
      <el-dialog
        :title="remarkTitle"
        :visible.sync="remarkVisible"
        width="800px"
        @close="resetRemarkForm"
        class="dialog-remark"
      >
        <el-form ref="remarkForm" :model="remarkForm" label-width="80px">
          <!-- 备注输入框 -->
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="remarkForm.remarks"
              type="textarea"
              :rows="4"
              placeholder="请输入备注内容"
              style="width: 100%"
            ></el-input>
          </el-form-item>

          <!-- 备注历史记录 -->
          <el-form-item label="备注历史">
            <el-table
              :data="remarkHistory"
              border
              style="width: 100%"
              :show-header="true"
            >
              <el-table-column prop="time" label="时间" width="200">
                <template slot-scope="scope">
                  {{ scope.row.time }}
                </template>
              </el-table-column>
              <el-table-column prop="operator" label="备注人" width="150">
                <template slot-scope="scope">
                  {{ scope.row.operator }}
                </template>
              </el-table-column>
              <el-table-column prop="content" label="备注" min-width="300">
                <template slot-scope="scope">
                  {{ scope.row.content }}
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="remarkVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemark">提交</el-button>
        </div>
      </el-dialog>
      <!-- 签到二维码弹窗 -->
    <el-dialog :title="qrCodeTitle" :visible.sync="qrCodeOpen" width="400px" append-to-body>
      <div class="qr-code-container">
        <div class="qr-code">
          <div class="mock-qr">
            <div class="mock-qr-corner"></div>
            <div class="mock-qr-corner" style="top: 10px; right: 10px; border-left: none; border-bottom: none;"></div>
            <div class="mock-qr-corner" style="bottom: 10px; left: 10px; border-right: none; border-top: none;"></div>
            <div class="mock-qr-content">
              <p>进班二维码</p>
            </div>
          </div>
        </div>
        <div class="qr-info">
          <p>有效期：15分钟</p>
        </div>
        <el-button type="primary" style="width: 100%; margin-top: 20px;" @click="refreshQrCode">刷新二维码</el-button>
      </div>
    </el-dialog>
    <!-- 学员通知弹窗 -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="noticeDialogVisible"
      width="50%"
      :before-close="handleNoticeDialogClose"
    >
      <el-form :model="noticeForm" ref="noticeForm" :rules="noticeRules">
        <el-form-item label="通知类型" prop="sendTypes">
          <el-checkbox-group v-model="noticeForm.sendTypes">
            <el-checkbox label="0">短信</el-checkbox>
            <el-checkbox label="1">门户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            type="textarea"
            v-model="noticeForm.content"
            placeholder="请输入通知内容"
            rows="6"
          ></el-input>
        </el-form-item>
        <el-form-item label="发送范围">
          <el-radio-group v-model="noticeForm.range" @change="handleRangeChange">
            <el-radio label="all">所有学员</el-radio>
            <el-radio label="selected">指定学员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="noticeForm.range === 'selected'"
          class="selected-users-form-item"
          prop="selectedUsers"
          :rules="[{ required: true, message: '请至少选择一个学员', trigger: 'change' }]"
        >
          <el-select
            v-model="noticeForm.selectedUsers"
            multiple
            placeholder="请输入学员姓名搜索并选择"
            filterable
            remote
            :remote-method="queryUsers"
            :loading="userLoading"
            style="width: 100%;"
            clearable
            @clear="handleSelectClear"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.studentId"
              :label="user.studentName"
              :value="user.studentId"
            >
              <span style="float: left">{{ user.studentName }}</span>
              <!-- <span style="float: right; color: #8492a6; font-size: 13px">
                {{ user.projectName }}
              </span> -->
              <span style="float: right; color: #8492a6; font-size: 13px">
                身份证号：{{ user.idNumber || '无证件号' }}
              </span>
            </el-option>
            <template #empty>
              <div style="text-align: center; color: #909399;">
                {{ userLoading ? '搜索中...' : '无匹配学员，请更换关键词' }}
              </div>
            </template>
          </el-select>
          <div class="selected-count" v-if="noticeForm.range === 'selected'">
            已选择 {{ noticeForm.selectedUsers.length }} 名学员
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNotice" :loading="noticeLoading">发送</el-button>
      </div>
    </el-dialog>
    <classSettlementDialog
      :visible.sync="showSettlement"
      :classId="settlementClassId"
      @confirm="handleSettlementConfirm"
      @close="handleSettlementClose"
    ></classSettlementDialog>
        </el-col>
  </div>
</template>

<script>
import {
  listTrainingClass,
  getTrainingClass,
  delTrainingClass,
  addTrainingClass,
  updateTrainingClass,
  importTrainingClass,
  getTrainingClassTemplate,
  trainingClassList,
  classHandover,
  myClasses
} from "@/api/training/TrainingClass";
import {
  getClassStudents,
} from "@/api/training/ClassStudent";
import { studentNoticeProcess } from "@/api/training/studentNotice.js";
import { projectTreeSelect } from "@/api/training/projects";
import { deptTreeSelect } from "@/api/system/user"
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import Pagination from "@/components/Pagination";
import { encrypt, decrypt } from '@/utils/encryption'
import { queryNonMemberUsers } from "@/api/system/user"
import { listRemarksByParams,addRemarks } from "@/api/training/remarks";
import classSettlementDialog from '@/components/class/classSettlementDialog.vue'
export default {
  name: "internalTraining",
  dicts: ["training_type", "class_status","start_up_type","bmlb","pub_mz","sys_user_sex",'units'],
  components: { Splitpanes, Pane, Pagination,classSettlementDialog },
  data() {
    return {
      //费用结算
      settlementClassId:"",
      showSettlement: false,
      // 人员选择数据源（班主任1和班主任2共用）
      memberOptions: [],
      // 二维码弹窗
      qrCodeOpen: false,
      qrCodeTitle: "签到二维码",
      currentPractice: {},
      //班级备注
      remarkVisible: false, // 控制备注弹窗显示
      remarkTitle: "报名备注", // 弹窗标题
      remarkForm: {
        remarks: "", // 当前备注内容
        registrationId: null, // 关联的报名ID
      },
      remarkTempId: "", //备注弹窗 参数ID
      exportDataTempIds: [], //导出数据IDs
      remarkHistory: [],
      selectionDto: null,
      // 基础状态
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      activeSearchTab: [],
      total: 0,
      TrainingClassList: [],
      dateRange: [],

      // 左侧树形菜单
      projectName: "",
      projectOptions: [],
      departmentData: [], // 部门树形数据
      defaultProps: { children: "children", label: "label" },
      treeProps: { children: 'children', label: 'label' }, // 树形选择框配置
      expandOnClickNode: true, // 树形选择框点击展开

      yearOptions: [], // 年份下拉选项（动态生成）
      showSearch: true, // 控制搜索栏显隐
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trainingProject: null,
        trainingClassCode: null,
        trainingClassName: null,
        classStatus: null,
        trainingYear: null,
        trainingSession: null,
        trainingType: null,
        startupType: null,
        signUpCategory: "special",
        trainingDepartment: null,
        totalQuota: null,
        registeredCount: null,
        registrationDate: null,
        startDate: null,
        endDate: null,
        trainingRegion: null,
        trainingVenue: null,
        needExam: null,
        projectId: null,
        headTeacherName: null,
      },

      // 新增班级弹窗状态与表单
      addOpen: false,
      addForm: {
        trainingClassId: null,
        signUpCategory: "special",
        trainingProject: null,
        trainingProjectNames: '',
        trainingClassCode: null,
        trainingClassName: null,
        trainingYear: new Date().getFullYear().toString(),
        trainingSession: null,
        startupType: null,
        trainingType: null,
        trainingDepartment: null,
        trainingDepartmentName: null,
        totalQuota: null,
        registeredCount: 0,
        registrationDate: null,
        startDate: null,
        endDate: null,
        trainingRegion: null,
        trainingAddress: null,
        trainingVenue: null,
        actualTrainingVenue: null,
        headTeacher1: '',
        headTeacher2: '',
        headTeacher1Name: null,
        headTeacher2Name: null,
        officialDocument: "",
        attachment: null,
        classStatus: null,
        courseIds: null,
        teacherIds: null,
        needExam: null,
        examPaperIds: null,
        remarks: null
      },

      // 编辑班级弹窗状态与表单
      editOpen: false,
      editForm: {
        trainingClassId: null,
        signUpCategory: "special",
        trainingProject: null,
        trainingProjectNames: '',
        trainingClassCode: null,
        trainingClassName: null,
        trainingYear: new Date().getFullYear().toString(),
        trainingSession: null,
        startupType: null,
        trainingType: null,
        trainingDepartment: null,
        trainingDepartmentName: null,
        totalQuota: null,
        registeredCount: 0,
        registrationDate: null,
        startDate: null,
        endDate: null,
        trainingRegion: null,
        trainingAddress: null,
        trainingVenue: null,
        actualTrainingVenue: null,
        headTeacher1: '',
        headTeacher2: '',
        headTeacher1Name: null,
        headTeacher2Name: null,
        officialDocument: "",
        attachment: null,
        classStatus: null,
        courseIds: null,
        teacherIds: null,
        needExam: null,
        examPaperIds: null,
        remarks: null
      },

      // 表单验证规则
      rules: {
        signUpCategory: [{ required: true, message: "请选择报名类别", trigger: "change" }],
        trainingAddress: [{ required: true, message: "请选择培训地址", trigger: "change" }],
        trainingProjectNames: [{ required: true, message: "请选择培训项目", trigger: "change" }],
        trainingClassCode: [{ required: true, message: "请输入培训班编号", trigger: "blur" }],
        trainingClassName: [{ required: true, message: "请输入培训班名称", trigger: "blur" }],
        trainingYear: [{ required: true, message: "请选择年份", trigger: "change" }],
        trainingSession: [{ required: true, message: "请输入期次", trigger: "blur" }],
        startupType: [{ required: true, message: "请选择开班类型", trigger: "change" }],
        trainingType: [{ required: true, message: "请选择培训类别", trigger: "change" }],
        trainingDepartmentName: [{ required: true, message: "请选择培训部门", trigger: "change" }],
        totalQuota: [{ required: true, message: "请输入培训人数", trigger: "blur" }],
        registrationDate: [{ required: true, message: "请选择报到日期", trigger: "change" }],
        startDate: [{ required: true, message: "请选择培训开始日期", trigger: "change" }],
        endDate: [{ required: true, message: "请选择培训截止日期", trigger: "change" }],
        trainingRegion: [{ required: true, message: "请输入培训地区", trigger: "blur" }],
        trainingVenue: [{ required: true, message: "请输入培训地点", trigger: "blur" }],
        headTeacher1: [{ required: true, message: "请输入班主任1", trigger: "blur" }],
        classStatus: [{ required: true, message: "请选择班级状态", trigger: "change" }],
        needExam: [{ required: true, message: "请选择是否考试", trigger: "change" }]
      },

      // 文件上传相关
      uploadUrl: "/api/file/upload", // 文件上传接口
      fileList: [],

      // 查看弹窗
      viewOpen: false,
      viewTitle: "查看培训班详情",
      viewForm: {},

      // 学员通知相关
      noticeDialogVisible: false,
      noticeLoading: false,
      noticeForm: {
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: [] ,

      },
      noticeRules: {
        range: [
          { required: true, message: '请选择发送途径', trigger: 'blur' }
        ],
        sendTypes: [
          { required: true, message: '请选择发送人员', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' },
          { max: 500, message: '内容不能超过500个字符', trigger: 'blur' }
        ]
      },

      // 用户选择相关
      userOptions: [],
      allUsers: [], // 存储所有学员数据，用于搜索和回显
      userLoading: false,

    };
  },
  watch: {
    projectName(val) {
      this.$refs.projectTree.filter(val);
    },
    // 监听弹窗显示状态，初始化数据
    noticeDialogVisible(newVal) {
      if (newVal) {
        this.initNoticeForm();
      }
    },
  },
  created() {
    const currentYear = new Date().getFullYear();
    this.yearOptions = Array.from({ length: 10 }, (_, i) => currentYear - i);
    this.initData();
    this.getMembersList(); // 初始化加载人员列表
    this.resetAddForm();
    this.resetEditForm();
  },

  computed: {
    // 生成近5年的年份列表（字符串类型）
    getYears() {
      const currentYear = new Date().getFullYear();
      return Array.from({ length: 5 }, (_, i) => (currentYear - i).toString());
    }
  },
  methods: {
    // 加载人员列表数据（共用逻辑）
    async getMembersList() {
      try {
        const userRes = await queryNonMemberUsers();
        this.memberOptions = userRes.rows || [];
      } catch (error) {
        console.error("人员数据加载失败：", error);
        this.$message.error("人员信息加载失败，请稍后重试");
        this.memberOptions = [];
      }
    },

    // 处理班主任选择变更，同步显示名称
    handleHeadTeacherChange(type, formType) {
      const targetForm = formType === 'add' ? this.addForm : this.editForm;
      const userId = targetForm[type];
      // 清空对应名称字段（包括清空选择的场景）
      targetForm[`${type}Name`] = userId ? '' : '';

      if (!userId) return;

      // 从人员列表中匹配用户信息，获取显示名称
      const matchedUser = this.memberOptions.find(
        user => user.userId === userId
      );
      if (matchedUser) {
        targetForm[`${type}Name`] = matchedUser.nickName || matchedUser.userName;
      }
    },
    // 班级备注
    async handleRemark() {
      var remarkListQuery = {
        foreignId:this.selectionDto[0].trainingClassId,
        remarkType: "3",
        };
        const res =await listRemarksByParams(remarkListQuery);
        // 获取该报名的备注历史
        this.remarkHistory =  res.rows.map(item =>{
          return {
                  time: item.createTime,
                  operator: item.createBy,
                  content: item.remarks,
                }
        })
        this.remarkVisible = true;
    },

    // 重置备注表单
    resetRemarkForm() {
      this.$nextTick(function() {
        if (this.$refs.remarkForm) {
          this.$refs.remarkForm.resetFields();
        }
      }.bind(this));
    },

    // 提交备注
    submitRemark() {
      this.$refs["remarkForm"].validate(async function(valid) {
        if (valid) {
          var remarkQuery = {
            foreignId:this.selectionDto[0].trainingClassId,
            remarkType: "3",
            remarks :this.remarkForm.remarks
          }
          const res = await addRemarks(remarkQuery)
          this.$message.success("备注提交成功");
          this.remarkVisible = false;
          this.getList(); // 刷新列表
        }
      }.bind(this));
    },
    // 初始化数据，确保项目树先加载
    async initData() {
      await Promise.all([this.getProjectTree(), this.getDepartmentTree()]);
      this.getList();
    },

    // 获取班级状态标签
    getClassStatusLabel(status) {
      const label = this.dict.label.class_status[status];
      // 若存在则返回标签，否则返回原始值
      return label !== undefined ? label : status;
    },

    // 获取培训类型标签
    getTrainingTypeLabel(type) {
      const label = this.dict.label.training_type[type];
      // 若存在则返回标签，否则返回原始值
      return label !== undefined ? label : type;
    },

    // 班级数据组新增方法
    handleUpdateSingle() {
      if (this.selectionDto && this.selectionDto.length === 1) {
        this.getEditClassData(this.selectionDto[0].trainingClassId);
      }
    },
    handleViewSingle() {
      this.$router.push({
        name: '内训班级维护',
        params: {
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleClassSatisfaction(){
      this.$router.push({
        name: '班级满意度',
        params: {
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleSetTeachers() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 3,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleSetMaterials() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 4,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleSetSupplies() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 5,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleSetExams() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 6,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleSetCertificates() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 7,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleSetTrainingPlans() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 8,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },

    // 班级交接功能
    handleClassHandover() {
      if(this.selectionDto[0].headTeacher2Name !== null &&
        this.selectionDto[0].headTeacher2Name !== undefined &&
        this.selectionDto[0].headTeacher2Name !== "" && this.statusStr(this.selectionDto[0].handoverStatus) !== "交接中" ) {

        this.$confirm(`确定将"${this.selectionDto[0].trainingClassName}" 交接给班主任2 "${this.selectionDto[0].headTeacher2Name}"`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async function() {
          try {
            const res =await classHandover({
              completeHandover:"false",
              trainingClassId:this.selectionDto[0].trainingClassId
            });
            this.$message.success(`班级 "${this.selectionDto[0].trainingClassName}" 已提交给 "${this.selectionDto[0].headTeacher2Name}",
            等待"${this.selectionDto[0].headTeacher2Name}"确定交接。`);

            // 刷新页面数据
            this.getList()
          } catch (error) {
            this.$message.error('班级交接失败，请重试');
          }
        }.bind(this)).catch(function() {
          this.$message.info('已取消班级交接操作');
        }.bind(this));

      } else {
        if(this.statusStr(this.selectionDto[0].handoverStatus) == "交接中"){
          this.$message.warning('班级已是交接中，请无重复交接');
        }else{
          this.$message.warning('班主任2未选择，请选择后再交接');
        }
      }
    },
    handleTrainingReservation() {
      this.$router.push({
        name: '实践预约情况',
        params: {
          className: this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          handoverStatus: this.statusStr(this.selectionDto[0].handoverStatus),
          trainingClassCode: this.selectionDto[0].trainingClassCode,
        }
      });
    },
// 初始化通知表单
    initNoticeForm() {
      this.noticeForm = {
        title: '',
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes:[],
      };

      // 如果有allUsers数据，自动设置所有学员
      if (this.allUsers.length > 0) {
        this.setAllStudents();
      } else {
        // 如果没有数据，重新加载学员数据
        this.loadStudentsData();
      }

      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.noticeForm) {
          this.$refs.noticeForm.clearValidate();
        }
      });
    },

    // 加载学员数据
    async loadStudentsData() {
      try {
        const res = await getClassStudents({
          trainingClassId: this.selectionDto[0].trainingClassId,
        });

        // 统一数据格式
        this.allUsers = res.rows.map(item => {
          const registration = item.registrationDto || {};
          return {
            studentId: registration.studentId || item.studentId,
            studentName: registration.studentName || item.studentName,
            projectName: registration.projectName || item.projectName,
            idNumber: registration.idNumber || item.idNumber,
          };
        }).filter(user => user.studentId && user.studentName); // 过滤掉无效数据

        this.userOptions = [...this.allUsers];

        // 如果当前是"所有学员"模式，更新selectedUsers
        if (this.noticeForm.range === 'all') {
          this.setAllStudents();
        }
      } catch (error) {
        console.error("加载学员数据失败：", error);
        this.$message.error("加载学员数据失败");
      }
    },

    // 处理发送范围变化
    handleRangeChange(newRange) {
      if (newRange === 'all') {
        // 切换到所有学员，自动选择全部
        this.setAllStudents();
      } else if (newRange === 'selected') {
        // 切换到指定学员，清空选择
        this.noticeForm.selectedUsers = [];
      }

      // 清除验证状态
      this.$nextTick(() => {
        if (this.$refs.noticeForm) {
          this.$refs.noticeForm.clearValidate('selectedUsers');
        }
      });
    },

    // 设置所有学员
    setAllStudents() {
      if (this.allUsers.length > 0) {
        this.noticeForm.selectedUsers = this.allUsers.map(user => user.studentId);
      }
    },

    // 处理选择器清空
    handleSelectClear() {
      this.noticeForm.selectedUsers = [];
    },
    // 处理学员通知
    handleStudentNotice() {
      this.noticeDialogVisible = true;
    },

    // 关闭通知弹窗
    handleNoticeDialogClose() {
      this.noticeDialogVisible = false;
    },

    // 提交通知
    submitNotice() {
      this.$refs.noticeForm.validate(async (valid) => {
        if (valid) {
          this.noticeLoading = true;
          try {
            // 1. 整理接口参数：关联表单和页面数据
            const noticeParams = {
              // 发送范围：all→sendType=1（空数组），selected→sendType=2（传选中ID）
              sendType: this.noticeForm.range === 'all' ? "1" : "2",
              studentIds: this.noticeForm.range === 'all' ? [] : this.noticeForm.selectedUsers,
              // 通知渠道：根据sendType（0=短信、1=门户、2=服务号）设置
              isSms: this.noticeForm.sendTypes.includes('0') ? "1" : "0", // 短信
              isPortal: this.noticeForm.sendTypes.includes('1') ? "1" : "0", // 门户
              isService: this.noticeForm.sendTypes.includes('2') ? "1" : "0", // 服务号（若启用）
              // 通知内容：从表单获取
              noticeContent: this.noticeForm.content,
              // 发送时间：动态生成当前时间（格式：YYYY-MM-DD HH:mm:ss）
              sendTime: new Date().toLocaleString('zh-CN', {
                year: 'numeric', month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit', second: '2-digit',
                hour12: false
              }).replace(/\//g, '-'),
              // 班级ID：从页面数据获取
              trainingClassId: this.selectionDto[0].trainingClassId
            };

            // 2. 调用接口
            const res = await studentNoticeProcess(noticeParams);

            // 3. 处理成功回调
            if (res.code === 200) { // 假设接口返回success字段表示成功
              this.$message.success("通知发送成功");
              this.noticeDialogVisible = false; // 关闭弹窗
            } else {
              this.$message.error("通知发送失败：" + (res.message || "未知错误"));
            }
          } catch (error) {
            // 4. 处理接口调用失败
            console.error("通知发送接口异常：", error);
            this.$message.error("通知发送失败，请稍后重试");
          } finally {
            // 5. 无论成功失败，关闭加载状态
            this.noticeLoading = false;
          }
        } else {
          this.$message.warning('请完善表单信息');
        }
      });
    },

    // 查询用户
    async queryUsers(query) {
      if (!query) {
        // 如果搜索为空，显示所有学员
        this.userOptions = [...this.allUsers];
        return;
      }

      this.userLoading = true;

      // 使用setTimeout模拟搜索延迟，实际项目中可以调用搜索接口
      setTimeout(() => {
        try {
          // 本地搜索过滤
          const filteredUsers = this.allUsers.filter(user =>
            user.studentName && user.studentName.includes(query)
          );
          this.userOptions = filteredUsers;
        } catch (error) {
          console.error("搜索学员失败：", error);
          this.userOptions = [];
        } finally {
          this.userLoading = false;
        }
      }, 300);
    },
    handleClassExam(){
      this.$router.push({
        name: '班级考试',
        params: {
          className: this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          handoverStatus: this.statusStr(this.selectionDto[0].handoverStatus),
          trainingClassCode: this.selectionDto[0].trainingClassCode,
        }
      });
    },
    handleClassExamArrange(){
      this.$router.push({
        name: '班级考试',
        params: {
          className: this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          handoverStatus: this.statusStr(this.selectionDto[0].handoverStatus),
          trainingClassCode: this.selectionDto[0].trainingClassCode,
        }
      });
    },

    handleSignInStatus() {
      this.$router.push({
        name: '签到统计',
        params: {
          className: this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          classStatus: this.statusStr(this.selectionDto[0].handoverStatus),
        }
      });
    },
    handleClassMaintain() {
      this.$router.push({
        name: '班级维护',
        params: {
          className: this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          classStatus: '未交接'
        }
      });
    },
    handleClassRemark() {
      this.handleRemark()
    },
    handleExportClassDetail() {
      this.$message.info("班级详情导出功能待实现");
    },

    handlePracticalAppointment(){
      this.$router.push({
        name: '实践预约',
        // params: {
        //   className: this.selectionDto[0].trainingClassName,
        //   classId: this.selectionDto[0].trainingClassId,
        //   classStatus: '未交接'
        // }
      });
    },
    //1+x项目
    handleMany(){
      this.$router.push({
        name: '1+x项目',
        params: {
          className: this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          classStatus: this.statusStr(this.selectionDto[0].handoverStatus),
        }
      });
    },


    // 视图与结算组新增方法
    toggleSort() {
      this.$message.info("隐藏/排序列功能待实现");
    },
    handleSettlementConfirm(data) {
      this.showSettlement=data
    },
    handleSettlementClose(data) {
      this.showSettlement=data
    },
    handleClassSettlement() {
      this.showSettlement= true
      this.settlementClassId=this.selectionDto[0].trainingClassId
      // this.$message.info("班级结算功能待实现");
    },
    handleFeeSettlement() {
      this.showSettlement= true
      this.settlementClassId=this.selectionDto[0].trainingClassId
    },
    handleExportFeeSettlement() {
      this.$message.info("费用结算导出功能待实现");
    },

    // 获取扁平化的项目选项
    getFlattenedProjectOptions() {
      const flatten = function(arr, result = []) {
        for (const item of arr) {
          result.push(item);
          if (item.children && item.children.length) {
            flatten(item.children, result);
          }
        }
        return result;
      };
      return flatten(this.projectOptions);
    },

    // 树形转平面的迭代方法，用于树形选择框
    optionData(array, result = []) {
      array.forEach(function(item) {
        result.push({ label: item.label, value: item.id })
        if (item.children && item.children.length !== 0) {
          this.optionData(item.children, result)
        }
      }.bind(this));
      return JSON.parse(JSON.stringify(result))
    },

    // 处理部门节点点击
    handleDeptNodeClick(node, formType) {
      const targetForm = formType === 'add' ? this.addForm : this.editForm;
      targetForm.trainingDepartmentName = node.label;
      targetForm.trainingDepartment = node.id;
      const targetSelectTree = this.$refs[`${formType}DeptSelectTree`];
      if (targetSelectTree) {
        targetSelectTree.blur();
      }
    },

    // 处理培训项目节点点击
    handleProjectNodeClick(node, formType) {
      const targetForm = formType === 'add' ? this.addForm : this.editForm;
      targetForm.trainingProjectNames = node.label;
      targetForm.trainingProject = node.id;
      const targetSelectTree = this.$refs[`${formType}ProjectSelectTree`];
      if (targetSelectTree) {
        targetSelectTree.blur();
      }
    },

    // 根据ID从树形数据中查找节点
    findNodeById(treeData, id) {
      for (const node of treeData) {
        if (node.id.toString() === id.toString()) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    // 基础列表方法
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      }
      trainingClassList(params).then(function(response) {
        // 确保返回数据中的状态字段为字符串类型
        this.TrainingClassList = response.rows.map(function(item) {
          return {
            ...item,
            classStatus: item.classStatus+"",
            trainingType: item.trainingType+"",
            needExam: item.needExam+""
          };
        });
        this.total = response.total;
        this.loading = false;
      }.bind(this));
    },

    handleRefresh() {
      this.getList();
      this.$message.success("列表已刷新");
    },

    // 左侧树形菜单方法
    getProjectTree() {
      return projectTreeSelect({}).then(function(response) {
        this.projectOptions = response.data;
      }.bind(this));
    },

    // 获取部门树形数据
    getDepartmentTree() {
      return deptTreeSelect().then(function(response) {
        this.departmentData = response.data;
      }.bind(this));
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    handleNodeClick(data) {
      this.queryParams.projectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList();
    },

    handleProjectSearch() {
      this.$refs.projectTree.filter(this.projectName);
    },

    // 搜索区域方法
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.loading = true;
      const params = { ...this.queryParams };
      trainingClassList(this.addDateRange(params, this.dateRange)).then(function(response) {
        // 确保返回数据中的状态字段为字符串类型
        this.TrainingClassList = response.rows.map(function(item) {
          return {
            ...item,
            classStatus: item.classStatus+"",
            trainingType: item.trainingType+"",
            needExam: item.needExam+""
          };
        });
        this.total = response.total;
        this.loading = false;
      }.bind(this));
    },

    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }
      this.dateRange = [];
      this.queryParams.projectId = null;
      this.$refs.projectTree.filter("");
      this.handleQuery();
    },

    toggleSearch() {
      this.showSearch = !this.showSearch;
    },

    // 选中数据处理
    handleSelectionChange(selection) {
      this.selectionDto = selection;
      this.ids = selection.map(function(item) {
        return item.trainingClassId;
      });
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 新增班级方法
    handleAdd() {
      // 先重置表单，再打开弹窗
      this.resetAddForm();
      this.addOpen = true;
      this.$nextTick(() => {
        // 重置新增弹窗的树形选择框
        if (this.$refs.addProjectSelectelTree) {
          this.$refs.addProjectSelectelTree.setCurrentKey(null);
        }
        if (this.$refs.addDeptSelectelTree) {
          this.$refs.addDeptSelectelTree.setCurrentKey(null);
        }
      });
    },

    // 重置新增表单
    resetAddForm() {
      this.addForm = {
        trainingClassId: null,
        signUpCategory: "special",
        trainingProject: null,
        trainingProjectNames: '',
        trainingClassCode: null,
        trainingClassName: null,
        trainingYear: new Date().getFullYear().toString(),
        trainingSession: null,
        startupType: null,
        trainingType: null,
        trainingDepartment: null,
        trainingDepartmentName: null,
        totalQuota: null,
        registeredCount: 0,
        registrationDate: null,
        startDate: null,
        endDate: null,
        trainingRegion: null,
        trainingAddress: null,
        trainingVenue: null,
        actualTrainingVenue: null,
        headTeacher1: '',
        headTeacher2: '',
        headTeacher1Name: null,
        headTeacher2Name: null,
        officialDocument: "",
        attachment: null,
        classStatus: null,
        courseIds: null,
        teacherIds: null,
        needExam: null,
        examPaperIds: null,
        remarks: null
      };
      this.$nextTick(() => {
        if (this.$refs.addForm) {
          this.$refs.addForm.clearValidate();
        }
      });
    },

    // 提交新增班级
    submitAddForm() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const submitData = { ...this.addForm };
          // 处理数字字段（如培训人数）
          if (submitData.totalQuota) {
            submitData.totalQuota = Number(submitData.totalQuota);
          }
          // 不考试时清空试卷ID
          if (submitData.needExam === '0') {
            submitData.examPaperIds = null;
          }
          try {
            await addTrainingClass(submitData);
            this.$modal.msgSuccess("新增班级成功");
            this.addOpen = false;
            this.getList(); // 刷新列表
          } catch (error) {
            this.$message.error("新增班级失败：" + (error.msg || "未知错误"));
          }
        }
      });
    },

    // 取消新增班级
    cancelAdd() {
      this.addOpen = false;
      this.$nextTick(() => {
        this.resetAddForm();
      });
    },

    // 获取编辑班级数据并打开弹窗
    async getEditClassData(classId) {
      // 确保人员列表已加载
      if (this.memberOptions.length === 0) {
        await this.getMembersList();
      }
      try {
        const response = await getTrainingClass(classId);
        let resData = { ...response.data };
        // 处理数据格式（转为字符串，适配下拉框）
        resData.classStatus = resData.classStatus != null ? resData.classStatus.toString() : '';
        resData.trainingType = resData.trainingType != null ? resData.trainingType.toString() : '';
        resData.needExam = resData.needExam != null ? resData.needExam.toString() : '';
        resData.headTeacher1 = resData.headTeacher1 != null ? resData.headTeacher1.toString() : '';
        resData.headTeacher2 = resData.headTeacher2 != null ? resData.headTeacher2.toString() : '';
        console.log(resData)

        // 回显培训部门名称
        if (resData.trainingDepartment) {
          const deptNode = this.findNodeById(this.departmentData, resData.trainingDepartment);
          resData.trainingDepartmentName = deptNode != null ? deptNode.label : '';
        }

        // 回显培训项目名称
        if (resData.trainingProject) {
          const projectNode = this.findNodeById(this.projectOptions, resData.trainingProject);
          resData.trainingProjectNames = projectNode != null ? projectNode.label : '';
        }
        // 回显班主任名称
        if (resData.headTeacher1) {
          const teacher1 = this.memberOptions.find(u => u.userId === resData.headTeacher1);
          resData.headTeacher1Name = teacher1 ? (teacher1.nickName || teacher1.userName) : '';
        }
        if (resData.headTeacher2) {
          const teacher2 = this.memberOptions.find(u => u.userId === resData.headTeacher2);
          resData.headTeacher2Name = teacher2 ? (teacher2.nickName || teacher2.userName) : '';
        }
        // 赋值给编辑表单
        this.editForm = resData;
        console.log(resData)
        this.editOpen = true;
        // 回显树形选择框选中状态
        this.$nextTick(() => {
          if (this.$refs.editProjectSelectelTree && resData.trainingProject) {
            this.$refs.editProjectSelectelTree.setCurrentKey(resData.trainingProject);
          }
          if (this.$refs.editDeptSelectelTree && resData.trainingDepartment) {
            this.$refs.editDeptSelectelTree.setCurrentKey(resData.trainingDepartment);
          }
        });
      } catch (error) {
        this.$message.error("加载班级数据失败：" + (error.msg || "未知错误"));
      }
    },

    // 提交编辑班级
    submitEditForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          const submitData = { ...this.editForm };
          // 处理数字字段
          if (submitData.totalQuota) {
            submitData.totalQuota = Number(submitData.totalQuota);
          }
          // 不考试时清空试卷ID
          if (submitData.needExam === '0') {
            submitData.examPaperIds = null;
          }
          try {
            await updateTrainingClass(submitData);
            this.$modal.msgSuccess("编辑班级成功");
            this.editOpen = false;
            this.getList(); // 刷新列表
          } catch (error) {
            this.$message.error("编辑班级失败：" + (error.msg || "未知错误"));
          }
        }
      });
    },

    // 重置编辑表单
    resetEditForm() {
      this.editForm = {
        trainingClassId: null,
        signUpCategory: "special",
        trainingProject: null,
        trainingProjectNames: '',
        trainingClassCode: null,
        trainingClassName: null,
        trainingYear: new Date().getFullYear().toString(),
        trainingSession: null,
        startupType: null,
        trainingType: null,
        trainingDepartment: null,
        trainingDepartmentName: null,
        totalQuota: null,
        registeredCount: 0,
        registrationDate: null,
        startDate: null,
        endDate: null,
        trainingRegion: null,
        trainingAddress: null,
        trainingVenue: null,
        actualTrainingVenue: null,
        headTeacher1: '',
        headTeacher2: '',
        headTeacher1Name: null,
        headTeacher2Name: null,
        officialDocument: "",
        attachment: null,
        classStatus: null,
        courseIds: null,
        teacherIds: null,
        needExam: null,
        examPaperIds: null,
        remarks: null
      };
      this.$nextTick(() => {
        if (this.$refs.editForm) {
          this.$refs.editForm.clearValidate();
        }
      });
    },

    // 取消编辑班级
    cancelEdit() {
      this.editOpen = false;
      this.$nextTick(() => {
        this.resetEditForm();
      });
    },

    // 删除方法
    handleDelete(row) {
      const trainingClassIds = row ? row.trainingClassId : this.ids;
      this.$modal.confirm(`是否确认删除选中的${row ? '1' : this.ids.length}个培训班？`).then(function() {
        return delTrainingClass(trainingClassIds);
      }.bind(this)).then(function() {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }.bind(this)).catch(function() {});
    },
     // 签到二维码
    handleSignInQr() {
      this.qrCodeOpen = true;
    },

    // 刷新二维码
    refreshQrCode() {
      this.$message.success("二维码已刷新，新的有效期为15分钟");
    },

    // 导出方法
    handleExport() {
      this.$confirm("是否确认导出所有符合条件的培训班数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        const params = { ...this.queryParams };
        if (this.dateRange && this.dateRange.length === 2) {
          params.startDate = this.dateRange[0];
          params.endDate = this.dateRange[1];
        }
        this.download('/api/TrainingClass/TrainingClass/export', params, `培训班数据_${new Date().getTime()}.xlsx`);
      }.bind(this));
    },

    // 文件上传方法
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.attachment = response.data.fileId;
        this.form.attachmentName = file.name;
        this.form.attachmentUrl = response.data.url;
        this.fileList = fileList;
        this.$message.success('文件上传成功');
      } else {
        this.$message.error('文件上传失败: ' + response.msg);
      }
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      if (fileList.length === 0) {
        this.form.attachment = null;
        this.form.attachmentName = null;
        this.form.attachmentUrl = null;
      }
    },

    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error('上传文件大小不能超过 20MB!');
        return false;
      }
      return true;
    },

    // 查看详情方法
    handleView(row) {
      getTrainingClass(row.trainingClassId).then(function(response) {
        let resData = { ...response.data };

        // 转换状态字段为字符串，便于显示标签
        resData.classStatus = resData.classStatus+"";
        resData.trainingType = resData.trainingType+"";
        resData.needExam = resData.needExam+"";

        // 回显培训部门名称
        if (resData.trainingDepartment) {
          const deptNode = this.findNodeById(this.departmentData, resData.trainingDepartment);
          resData.trainingDepartmentName = deptNode ? deptNode.label : '未知部门';
        } else {
          resData.trainingDepartmentName = '未设置';
        }

        // 回显培训项目名称
        if (resData.trainingProject) {
          const projectNode = this.findNodeById(this.projectOptions, resData.trainingProject);
          resData.trainingProjectNames = projectNode ? projectNode.label : '未知项目';
        } else {
          resData.trainingProjectNames = '未设置';
        }

        this.viewForm = resData;
        this.viewOpen = true;
        this.viewTitle = `查看培训班详情：${resData.trainingClassName}`;
      }.bind(this));
    },

    cancelView() {
      this.viewOpen = false;
    },

    handleViewStudents(row) {
      this.$message.info(`进入${row.trainingClassName}的学员管理页面`);
    },

    // 其他功能按钮方法
    handleSetMembers() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 1,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    handleSetClassStatus(){
      if(this.selectionDto[0].classStatus ==="2"){
        this.$message.info('此班级已结业');
        return
      }else if(this.selectionDto[0].classStatus ==="0"){
        this.$message.info('此班级未开班，无法结业');
        return
      }else if(this.selectionDto[0].classStatus ==="1"){
        this.$message.info('此班级已取消，无法结业');
        return
      }
      this.$confirm(`确定让这个班级结业？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await updateTrainingClass({trainingClassId:this.selectionDto[0].trainingClassId,classStatus:"2"})
          this.$message.info('班级结业完成');
          this.getList()
       } catch (error) {
          console.error('班级结业操作出错:', error);
          this.$message.error('班级结业操作失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消班级结业操作');
      });
    },
    handleSetCourses() {
      this.$router.push({
        name: '班级设置',
        params: {
          id: 2,
          classId: this.selectionDto[0].trainingClassId,
        }
      });
    },
    async handleStudentEnter() {
      const res =await getTrainingClass(this.selectionDto[0].trainingClassId)
      this.$router.push({
        name: '学员进出班管理',
        params: {
          className:this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          handoverStatus: this.statusStr(this.selectionDto[0].handoverStatus),
          projectId:res.data.trainingProject,
          trainingClassCode:this.selectionDto[0].trainingClassCode
        }
      });
    },
    statusStr(id){
      if(id === "0"){
        return "未交接"
      }else if(id === "1"){
        return "交接中"
      }else if(id === "2"){
        return  "已交接"
      }else{
        return "交接状态有误"
      }
    },
    handleClassStudents() {
      // 准备要传递的数据
      const paramsData = {
        // className: this.selectionDto[0].trainingClassName,
        classId: this.selectionDto[0].trainingClassId,
        // handoverStatus: this.statusStr(this.selectionDto[0].handoverStatus),
        // trainingClassCode: this.selectionDto[0].trainingClassCode,
        // projectId:this.selectionDto[0].trainingProject,
      }

      // 加密参数
      // const encryptedParams = encrypt(paramsData)

      this.$router.push({
        name: '内训学员',
        params: paramsData
      });
    },
    handleSignIn() {
      this.$router.push({
        name: '签到',
        params: {
          className: this.selectionDto[0].trainingClassName,
          classId: this.selectionDto[0].trainingClassId,
          trainingClassCode: this.selectionDto[0].trainingClassCode,
          handoverStatus: this.statusStr(this.selectionDto[0].handoverStatus),
        }
      });
    }
  },

  mounted() {
    // 初始化时同步树形组件选中状态
    this.$nextTick(function() {
      if (this.$refs.projectSelectelTree && this.form.trainingProject) {
        this.$refs.projectSelectelTree.setCurrentKey(this.form.trainingProject);
      }
    }.bind(this));
  },
};
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.head-container {
  padding: 0 10px;
}

.tree-container {
  height: calc(100vh - 80px);
  overflow-y:  auto;
  padding: 10px;
  border-right: 1px solid #e6e6e6;
}

/* 高级搜索区域样式 */
.el-advanced-search-container {
  margin-bottom: 5px;
  /* padding: 10px; */
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-advanced-search-form {
  display: flex;
  flex-wrap: wrap;
}

/* 按钮组样式 */
.el-button-group {
  margin-bottom: 5px;
}

.el-button-group .el-button {
  padding: 6px 10px;
}

/* 表格样式 */
.el-table {
  margin-bottom: 15px;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

/* 表单分区样式 */
.form-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.section-title {
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #e6e6e6;
  font-size: 16px;
  color: #1890ff;
}

.form-row {
  margin-bottom: 15px;
}

/* 树形选择框样式 */
.main-select-tree {
  position: relative;
}

/* .main-select-el-tree {
  position: absolute;
  top: 40px;
  left: 0;
  z-index: 1000;
  width: 100%;
  max-height: 300px;
  overflow-y: auto;
  padding: 5px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
} */

/* 弹窗样式 */
.dialog-training-class .el-form-item {
  margin-bottom: 15px;
}

.dialog-view .view-form .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

/* 备注弹窗样式 */
.dialog-remark .el-textarea {
  width: 100%;
}

/* 二维码容器样式 */
.qr-code-container {
  text-align: center;
  padding: 20px 0;
}

.mock-qr {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 0 auto;
  background-color: #fff;
  border: 1px solid #e6e6e6;
}

.mock-qr-corner {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 30px;
  height: 30px;
  border: 3px solid #000;
}

.mock-qr-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.qr-info {
  margin-top: 15px;
  color: #666;
}

/* 学员通知弹窗样式 */
.selected-users-form-item {
  margin-top: 10px;
}

.selected-count {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}
</style>
